package classes
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	public class TagCloudHandler extends EventDispatcher
	{
		private static var instance:TagCloudHandler;
		private var _lastResult:ArrayCollection;
		
		[Bindable ("tagCloudResult")]
		public function get lastResult():ArrayCollection{
			return _lastResult;
		}
		
		public function TagCloudHandler(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		public function getTagCloudData():void{
			dispatchEvent(new Event("gettingTagCloud"));
			var servletReq:HTTPService = new HTTPService();
			servletReq.method = "GET";
			servletReq.url = Settings.getInstance().tagCloudServletURL;
			servletReq.addEventListener(ResultEvent.RESULT, tagCloudResultHandler);
			servletReq.send();
		}
		
		private function tagCloudResultHandler(event:ResultEvent):void{
			_lastResult = new ArrayCollection();
			if(event.result.toString() == "FAIL"){
				dispatchEvent(new Event("tagCloudError"));
				return;
			}else{
				if(getQualifiedClassName(event.result.tags.tag)=="mx.utils::ObjectProxy"){
					_lastResult.addItem({tag: event.result.tags.tag.name.toString(), occurrences: Number(event.result.tags.tag.occurrences)});
				}else for each(var item:Object in event.result.tags.tag){
					_lastResult.addItem({tag: item.name.toString(), occurrences: Number(item.occurrences.toString())});
				}
				dispatchEvent(new ResultEvent("tagCloudResult",false,true,{result: _lastResult, maxOccurrences:event.result.tags.biggest}));
			}
		}
		
		public static function getInstance():TagCloudHandler{
			if(instance == null)
				instance = new TagCloudHandler();
			return instance;
		}
	}
}